import os
import django

# 设置 Django 环境
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'knowledge_site.settings')
django.setup()

from core.models import Category

def update_nav_categories():
    """更新导航分类"""
    # 获取运维知识库分类
    try:
        root = Category.objects.get(slug='ops')
        print(f'找到根分类: {root.title}')
        
        # 更新根分类
        root.is_nav = True
        root.nav_sort = 0
        root.nav_path = '/'
        root.save()
        print(f'已更新根分类 "{root.title}" 为导航分类')
        
        # 获取二级分类
        second_level_categories = Category.objects.filter(parent=root)
        print(f'找到 {second_level_categories.count()} 个二级分类')
        
        # 更新为导航分类
        for index, category in enumerate(second_level_categories):
            category.is_nav = True
            category.nav_sort = index + 1  # 从1开始，因为根分类是0
            category.nav_path = f'/category/{category.slug}'  # 修改导航路径格式
            category.save()
            print(f'已更新分类 "{category.title}" 为导航分类')
            
    except Category.DoesNotExist:
        print('未找到根分类')

if __name__ == '__main__':
    print('开始更新导航分类...')
    update_nav_categories()
    print('更新完成！') 